<template>
  <div class="mini-container">
    <!-- 顶部栏 -->
    <div class="top-bar">
      <div class="content">
        <div class="logo"></div>
        <div class="currencies">
          <!-- <span class="cur-block">{{$t('capital.currency')}}：{{$t('menu.USD')}}</span> -->
					<span class="cur-block">{{ $t('capital.currency') }}：{{
					     money.currencyId === 1
					       ? $t('menu.RMB')
					       : money.currencyId === 3
					       ? $t('menu.USD')
					       : $t('menu.HKD')
					   }}</span>
          <span class="cur-block">{{$t('capital.totalProfitAndLoss')}}：{{totalFloat}}</span>
          <span lass="cur-block">{{$t('capital.enableBalance')}}：{{money.accountBalance}}</span>
        </div>
      </div>
      <div
        class="back"
        @click="backHome(1)"
        :title="$t('menu.zoom')"
      >
        <svg-icon icon-class="max" />
      </div>
    </div>
    <!-- 迷你悬浮窗主体部分 -->
    <div class="mini-content">
      <div class="order-form">
        <!-- 合约 -->
        <div class="form-item">
          <div class="item-label">{{$t('trade.contract')}}</div>
          <div class="item-body">
            <i-select
              v-model="conid"
              @on-change="selectContract"
              :placeholder="$t('trade.selectContract')"
            >
              <i-option
                v-for="item in contractlist"
                :value="item.heyue_id"
                :key="item.heyue_id"
              >{{item.heyue_name}}</i-option>
            </i-select>
          </div>
        </div>
        <!-- 手数 -->
        <div class="form-item">
          <div class="item-label">{{$t('trade.number')}}</div>
          <div class="item-body">
            <span
              class="less el-icon-minus"
              @click="calculateStep(1, 0)"
            ></span>
            <i-input
              type="number"
              class="compute-input"
              v-model="hands"
              :placeholder="$t('trade.number')"
            />
            <span
              class="add el-icon-plus"
              @click="calculateStep(1, 1)"
            ></span>
          </div>
        </div>
        <!-- 市价/挂单价/对手价 -->
        <div class="form-item">
          <div class="item-label">
            <span
              class="opt"
              :class="{on: priceType === '1'}"
              @click="switchPrice('1')"
              :title="$t('trade.marketPrice')"
            >市价</span>
            <span
              class="opt"
              :class="{on: priceType === '2'}"
              @click="switchPrice('2')"
              :title="$t('trade.restingOrder')"
            >挂单价</span>
            <span
              class="opt"
              :class="{on: priceType === '3'}"
              @click="switchPrice('3')"
              :title="$t('trade.rivalPrice')"
            >对手价</span>
          </div>
          <div
            class="item-body"
            v-if="priceType === '2' "
          >
            <span
              class="less el-icon-minus"
              @click="calculateStep(2, 0)"
            ></span>
            <i-input
              type="number"
              class="compute-input"
              v-model="price"
              :placeholder="priceType === '1' ? $t('trade.rivalPrice'):$t('trade.priceP')"
            />
            <span
              class="add el-icon-plus"
              @click="calculateStep(2, 1)"
            ></span>
          </div>
          <div
            class="market-price"
            v-else
          >{{priceType === '1' ? $t('trade.marketPrice') : $t('trade.rivalPrice')}}</div>
        </div>
        <!-- 当前行情 -->
        <div class="form-item market">
          <div class="item-buy">
            {{$t('enum.buy')}}
            <span
              class="buy"
              title
            >{{latestBuy}}</span>
          </div>
          <div class="item-sell">
            {{$t('enum.sell')}}
            <span
              class="sell"
              title
            >{{latestSell}}</span>
          </div>
        </div>
      </div>
      <div class="btn-group">
        <!-- 买 -->
        <div
          class="handle-btn"
          @click="handleBtns(1)"
        >
          <div class="btn-price">
            <!-- 市价 -->
            <span v-if="priceType==='1'">{{$t('trade.marketPrice')}}</span>
            <!-- 挂单价 -->
            <span v-if="priceType==='2'">{{price}}</span>
            <!-- 对手价 -->
            <span v-if="priceType==='3'">{{latestSell}}</span>
          </div>
          <div class="btn-text buy">{{$t('trade.buy')}}</div>
        </div>
        <!-- 卖 -->
        <div
          class="handle-btn"
          @click="handleBtns(2)"
        >
          <div class="btn-price">
            <!-- 市价 -->
            <span v-if="priceType==='1'">{{$t('trade.marketPrice')}}</span>
            <!-- 挂单价 -->
            <span v-if="priceType==='2'">{{price}}</span>
            <!-- 对手价 -->
            <span v-if="priceType==='3'">{{latestBuy}}</span>
          </div>
          <div class="btn-text sell">{{$t('trade.sell')}}</div>
        </div>
        <!-- 平 -->
        <div
          class="handle-btn"
          :class="handleClass"
          @click="handleBtns(3)"
        >
          <div class="btn-price">
            <!-- 市价 -->
            <span v-if="priceType==='1'">{{$t('trade.marketPrice')}}</span>
            <!-- 挂单价 -->
            <span v-if="priceType==='2'">{{price}}</span>
            <!-- 对手价 -->
            <span v-if="priceType==='3'">{{latestPrice}}</span>
          </div>
          <div class="btn-text open">{{$t('trade.close')}}</div>
        </div>
        <!-- 显示报表 -->
        <div
          class="handle-btn show-report"
          @click="showReport"
        >显示报表</div>
      </div>
    </div>
    <!-- 报表部分 -->
    <div class="mini-report">
      <Tabs size="small">
        <TabPane label="持仓单">
          <div class="open-trades">
            <!-- 持仓单列表 -->
            <div class="table-box">
              <table
                border="0"
                cellspacing="0"
                cellpadding="0"
                class="dTable"
              >
                <thead>
                  <tr>
                    <th>{{$t('trade.contract')}}</th>
                    <th>{{$t('trade.transition')}}</th>
                    <th>{{$t('trade.position')}}</th>
                    <th>{{$t('trade.openPrice')}}</th>
                    <th>{{$t('capital.computedDetailProfitAndLoss')}}</th>
                    <th>{{$t('trade.stopLossAmount')}}</th>
                    <th>{{$t('trade.takeProfitAmount')}}</th>
                  </tr>
                </thead>
                <!-- 明细列表 -->
                <tbody>
                  <!-- 无数据展示 -->
                  <tr
                    v-if="showPosList.length === 0"
                    class="noneInfo"
                  >
                    <td>{{this.$t('msg.noEntrustRecord')}}</td>
                  </tr>
                  <!-- 数据列表 -->
                  <tr
                    v-else
                    v-for="(item, index) in showPosList"
                    :key="item.ID"
                    :class="{active:index === ponIndex}"
                    @click="switchPosTr(index, item)"
                    @dblclick="quickClosing(2)"
                  >
                    <!-- 合约名称 -->
                    <td>
                      <div v-if="item.Name">{{item.Name}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 买卖 -->
                    <td>
                      <div v-if="item.Business">{{item.Business}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 持仓量 -->
                    <td>
                      <div v-if="item.Quantity">{{item.Quantity}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 开仓价 -->
                    <td>
                      <div v-if="item.AveragePrice">{{item.AveragePrice}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 逐笔盈浮 -->
                    <td>
                      <div
                        v-if="item.Floating"
                        :class="{pricerise: parseFloat(item.Floating) > 0, pricefall: parseFloat(item.Floating) < 0}"
                      >{{item.Floating}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 止损金额 -->
                    <td>
                      <div v-if="fullstoplist[item.ID] && fullstoplist[item.ID].LossAmount">{{fullstoplist[item.ID].LossAmount}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 止盈金额 -->
                    <td>
                      <div v-if="fullstoplist[item.ID] && fullstoplist[item.ID].ProfitAmount">{{fullstoplist[item.ID].ProfitAmount}}</div>
                      <div v-else>--</div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <!-- 持仓单操作 -->
            <div class="handle-box">
              <!-- 全部平仓 -->
              <span
                class="btn"
                @click="operationAll(1)"
              >{{$t('trade.allClose')}}</span>
              <!-- 快捷平仓 -->
              <span
                class="btn"
                @click="quickClosing(1)"
              >{{$t('trade.quickClose')}}</span>
              <!-- 快捷反手 -->
              <span
                class="btn"
                @click="Backhand"
              >{{$t('trade.quickBackhand')}}</span>
              <!-- 快捷锁仓 -->
              <span
                class="btn"
                @click="quickLock"
              >{{$t('trade.quickLock')}}</span>
            </div>
          </div>
        </TabPane>
        <TabPane label="委托单">
          <div class="order-ticket">
            <!-- 委托单列表 -->
            <div class="table-box">
              <table
                border="0"
                cellspacing="0"
                cellpadding="0"
                class="dTable order"
              >
                <thead>
                  <tr>
                    <th>{{$t('trade.contract')}}</th>
                    <th>{{$t('trade.status')}}</th>
                    <th>{{$t('trade.transition')}}</th>
                    <th>{{$t('trade.openClose')}}</th>
                    <th>{{$t('trade.entrustPrice')}}</th>
                    <th>{{$t('trade.entrustType')}}</th>
                    <th>{{$t('trade.entrustVol')}}</th>
                    <th>{{$t('trade.averagePrice')}}</th>
                    <th>{{$t('trade.numbering')}}</th>
                    <th>{{$t('trade.entrustTime')}}</th>
                    <th>{{$t('trade.dealTime')}}</th>
                  </tr>
                </thead>
                <tbody>
                  <!-- 无数据时展示 -->
                  <tr
                    v-if="commissionlist.length === 0"
                    class="noneInfo"
                  >
                    <td>{{$t('msg.noData')}}</td>
                  </tr>
                  <!-- 数据列表 -->
                  <tr
                    v-else
                    v-for="(item, index) in commissionlist"
                    :key="item.Numbering"
                    :class="{active:index === comIndex}"
                    @click="switchComTr(index)"
                  >
                    <!-- 合约名称 -->
                    <td>
                      <div
                        v-if="item.Name"
                        :title="item.Name"
                      >{{item.Name}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 状态 -->
                    <td>
                      <div v-if="item.Status">{{item.Status}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 买卖 -->
                    <td>
                      <div v-if="item.Business">{{item.Business}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 开平 -->
                    <td>
                      <div v-if="item.Kaiping">{{item.Kaiping}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 委托价 -->
                    <td>
                      <div v-if="item.ReportPrice">{{item.ReportPrice}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 委托类型 -->
                    <td>
                      <div v-if="item.Category">{{item.Category}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 委托量 -->
                    <td>
                      <div v-if="item.ReportHand">{{item.ReportHand}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 成交均价 -->
                    <td>
                      <div v-if="item.AveragePrice">{{item.AveragePrice}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 委托号 -->
                    <td :title="item.Numbering">
                      <div v-if="item.Numbering">{{item.Numbering}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 委托时间 -->
                    <td>
                      <div
                        v-if="item.DateTime && item.DateTime !== '0'"
                        :title="item.DateTime"
                      >{{item.DateTime}}</div>
                      <div v-else>--</div>
                    </td>
                    <!-- 成交时间 -->
                    <td>
                      <div
                        v-if="item.LastTime && item.LastTime !== '0'"
                        :title="item.LastTime"
                      >{{item.LastTime}}</div>
                      <div v-else>--</div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <!-- 委托单操作 -->
            <div class="handle-box">
              <span
                class="btn"
                @click="operationAll(2)"
              >{{$t('trade.allCancelOrder')}}</span>
              <span
                class="btn"
                @click="withdrawal"
              >{{$t('trade.cancelOrder')}}</span>
            </div>
          </div>
        </TabPane>
      </Tabs>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { Select, Option, Input, Tabs, TabPane } from "iview";
import * as trade from "../../request/trade";
import { obtainLength } from "../../utils/auth";
const { ipcRenderer } = require("electron");

export default {
  name: "mini",
  components: {
    Tabs,
    TabPane,
    ISelect: Select,
    IOption: Option,
    IInput: Input
  },
  computed: {
    ...mapGetters([
      "setList",
      "userinfo",
      "positionlist",
      "commissionlist",
      "contractlist",
      "actcontract",
      "fullstoplist",
      "latestMarket",
      "productlist",
      "dbclickEve",
      "oldBounds",
      "moneylist",
      "winSnap",
      "trade"
    ]),
    handleClass () {
      if (this.ponIndex === -1) {
        return ["buy-disable"];
      }
      if (
        this.showPosList[this.ponIndex] !== undefined &&
        this.showPosList[this.ponIndex].CanBeFlat <= 0
      ) {
        return ["buy-disable"];
      }
      // console.log(this.conid);
      if (
        this.showPosList[this.ponIndex] &&
        this.showPosList[this.ponIndex].ContractID !== this.conid
      ) {
        return ["buy-disable"];
      }
      return [];
    }
  },
  watch: {
    setList(val) {
			// console.log('setlist', val)
		
			let _actcontract = this.actcontract != null ? this.actcontract : this.contractlist[0].heyue_id
			if (val) {
				let _list = val
				for (let i = 0; i < _list.length; i++) {
					if (_list[i][4] === _actcontract) {
						this.stopScore = _list[i][2]
						this.stopLoss = _list[i][3]
					}
				}
			}
		},
    positionlist: {
      handler (newVal) {
        // 持仓列表
        // 判断当前选中的合约是否存在，如果不存在则清空
        if (
          !newVal[this.ponIndex] ||
          newVal[this.ponIndex].ContractID !== this.actcontract
        ) {
          this.ponIndex = -1;
        }
        // 如果当前数据不存在或者数据为空数组，将当前展示的明细列表和汇总列表都置空
        if (!newVal || newVal.length === 0) {
          this.showPosList = [];
          this.showCollectList = [];
          return;
        }
        // console.log(newVal);
        // 利用map生成新数据存储地址，避免在vuex外改变状态
        // 明细持仓列表
        let newData = newVal.map(v => {
          let nowObj = {
            ...v
          };
          return nowObj;
        });
        this.showPosList = newData;
        this.getCollectList(newData);
      },
      deep: true,
      immediate: true
    },
    commissionlist: {
      handler (newVal) {
        // console.log('当前委托单接收', newVal)
        if (!newVal[this.comIndex]) {
          this.comIndex = -1;
        }
      },
      deep: true,
      immediate: true
    },
    actcontract: {
      handler (newVal, oldVal) {
        // console.log("当前合约id", newVal);
        // 这里是主页列表选中合约是否会影响当前合约变化
        if (newVal === undefined) {
          return;
        }
        // console.log(this.$store.getters.productlist.length)
        for (const item of this.productlist) {
          if (item.ContractID === newVal) {
            // console.log('当前合约名称： ' + item.Name)
            // console.log("当前合约最小波动： " + item.Minimum);
            this.nowMinimum = parseFloat(item.Minimum);
            this.accuracy = obtainLength(item.Minimum);
            // console.log('当前最小波动精度aa', this.accuracy)
          }
        }
        // 合约号无变化
        if (newVal === oldVal) {
          return;
        }
        // 合约变化，将id赋值给select
        this.conid = newVal;
        if (this.priceType === "2") {
          this.price = this.latestPrice;
        }
      },
      immediate: true // 最初绑定值的时候也执行handler函数
    },
    latestMarket: {
      handler (newVal) {
        let that = this;
        let priceList = {}; // 最新价数据提取暂存
        // console.log(newVal)
        //  console.log(this.conid)
        for (const latest of newVal) {
          priceList[latest.heyue_id] = latest.currentPrice;
          // 更新左侧表单中选中的合约的最新价格
          // console.log('当前数据', latest)
          if (this.conid === latest.heyue_id) {
            this.latestPrice = latest.currentPrice; // 最新价
            this.latestSell = latest.seller1; // 卖
            this.latestBuy = latest.buy1; // 买
          }
        }

        // 只有持仓列表有数据才执行
        if (this.showPosList.length === 0) {
          return;
        }

        // 遍历并计算浮动盈亏，将之存储
        let totalFloat = 0;
        for (const item of this.showPosList) {
          let Floating = 0; // 当前浮盈
          let latestPrice = priceList[item.ContractID];
          if (item.BusCode === "2") {
            // 卖: (开仓价 - 最新价 )* 持仓量 * 合约乘数
            Floating =
              (item.AveragePrice - latestPrice) *
              item.Quantity *
              item.Multiplier;
          } else if (item.BusCode === "1") {
            // 买: (最新价 - 开仓价 )* 持仓量 * 合约乘数
            Floating =
              (latestPrice - item.AveragePrice) *
              item.Quantity *
              item.Multiplier;
          }
          // let nowAcc = obtainLength(item.Minimum); // 当前合约根据最小波动得出的精度
          Floating = Floating.toFixed(2);
          totalFloat += Floating*1
          // 明细浮盈
          that.floatingList[item.ID] = Floating;
        }
        this.totalFloat = (totalFloat*1).toFixed(2)
        // 更新浮盈状态
        const newFlList = this.showPosList.map(v => {
          return {            ...v,
            Floating: that.floatingList[v.ID]
          }
        })

        this.showPosList = newFlList
      },
      deep: true,
      immediate: true
    },
    conid: {
      handler (newVal, oldVal) {
        let _this = this;
        if (newVal === oldVal) {
          return;
        }
        // 合约变化后初始化各个值，更新最小波动
         this.priceType = "1"; // 市价
        this.nowPrice = ""; // 当前价格(左侧表单中)
        this.hands = 1; // 手数,最小1笔
        this.stopScore = 0; // 止盈点数
        this.stopLoss = 0; // 止损点数
        // console.log(this.productlist);
        if (newVal === undefined || newVal === null) {
          return;
        }
        if (this.productlist.length === 0) return
        let nowCobj = this.productlist.find(v => v.ContractID === newVal);
        // console.log(nowCobj)
        if (nowCobj.Name) {
          this.$store.commit("panel/SET_SELNAME", nowCobj.Name);
          if (this.setList) {
            var setList = this.setList
            for (let i = 0; i < setList.length; i++) {
              if (setList[i][1] == nowCobj.Name) {
                this.stopScore = setList[i][2]
                this.stopLoss = setList[i][3];
              }
            }
          }
        }
        // console.log(this.stopScore, this.stopLoss)
      },
      immediate: true
    },
    moneylist: {
      handler (newVal) {
        // this.money
        if (newVal === undefined || newVal === null || !newVal) {
          return;
        }

        if (!newVal.length || newVal.length === 0) {
          return;
        }
        let curObj = newVal.find(v => v.currencyId === 1);
        // console.log("money:", curObj)
        this.money = curObj;
      },
      immediate: true
    },
    priceType (val) {
      if (val === "2") {
        this.price = this.latestPrice;
      }
    },
    trade (newVal, oldVal) {
      // console.log('当前交易的连接状态', newVal)
      if (newVal === false && oldVal === true) {
        this.backHome()
      }
    }
  },
  data () {
    return {
      hands: 1, //手数
      price: 0, // 当前价格
      stopScore: 0, // 止盈点数 (下单表单中)
      stopLoss: 0, // 止损点数 (下单表单中)
      conid: "", // 当前选中合约id
      priceType: "1", // 当前选中的价格类型: 1市价2挂单价3对手价
      isShowRep: false, // 当前显示的持仓列表 // 是否展示报表
      floatingList: {}, // 浮盈数据存储
      showPosList: [], // 持仓单列表
      showCollectList: [], // 当前汇总持仓列表
      ponIndex: -1, // 持仓单选中
      comIndex: -1, // 委托单选中
      latestPrice: 0, // 当前组件选择的合约的最新价，根据行情更新(表单中使用)
      latestBuy: 0, // 当前组件选择的合约的买价，根据行情更新(表单中使用)
      latestSell: 0, // 当前组件选择的合约的卖价，根据行情更新(表单中使用)
      nowMinimum: 0, // 当前选中的合约的最小波动(左侧表单中)
      accuracy: 0, // 挂单价精度
      money: {}, // 资金状况,
      totalFloat: 0
    };
  },
  mounted () {
    // this.$store.commit("panel/SET_WINSNAP", true);
    // 判断用户是否登录了，如果没有登录，需要返回主页并将窗口最大化
    if (this.userinfo === null || !this.userinfo) {
      this.backHome(2);
    }
    // 判断当前报表展示状态
    if (this.isShowRep) {
      // console.log('报表展示')
      ipcRenderer.send("win-msg", "show-report"); // 展示报表
    } else {
      // console.log('关闭报表')
      ipcRenderer.send("win-msg", "hide-report"); // 关闭报表
    }
    // this.stopScore=	localStorage.zhiying?localStorage.zhiying:0
    // this.stopLoss=	localStorage.zhisun?localStorage.zhisun:0
    // require('web-frame').setZoomLevelLimits(1, 1);
  },
  methods: {
    getCollectList (arr) {
      // console.log("当前传入", arr);
      let idArr = arr.map(v => {
        if (v.BusCode === "买") {
          v.BusCode = "1";
        }
        if (v.BusCode === "卖") {
          v.BusCode = "2";
        }
        return v.ContractID;
      });
      let setArr = new Set(idArr);
      // 生成汇总持仓列表
      // 先数组去重,保证合约唯一
      let noRepeat = Array.from(setArr); // 无重复Set转换成数组
      let collectList = []; // 汇总数据
      // console.log("无重复数组", noRepeat);
      for (const val of noRepeat) {
        let buyObj = {}; // 买方向暂存
        let buyQuantity = 0; // 持仓量（买方向）
        let buyPrice = 0; // 价格汇总（买方向）

        let sellObj = {}; // 卖方向数据暂存
        let sellQuantity = 0; // 持仓量（卖方向）
        let sellPrice = 0; // 价格汇总（卖方向）

        let findArr = arr.find(item => item.ContractID === val);

        let itemAcc = 0;
        for (const item of arr) {
          itemAcc = obtainLength(item.Minimum);
          // console.log("汇总精度", itemAcc);
          // 买方向数据筛选
          if (
            item.ContractID === val &&
            (item.BusCode === "1" || item.BusCode === "买")
          ) {
            buyObj = {
              ...item
            };
            let bQua = parseFloat(item.Quantity);
            let bPri = parseFloat(item.AveragePrice);
            buyQuantity += bQua;
            buyPrice = buyPrice + bPri * bQua;
          }

          // 卖方向数据筛选
          if (
            item.ContractID === val &&
            (item.BusCode === "2" || item.BusCode === "卖")
          ) {
            sellObj = {
              ...item
            };
            let sQua = parseFloat(item.Quantity);
            let sPri = parseFloat(item.AveragePrice);
            sellQuantity += sQua;
            sellPrice = sellPrice + sPri * sQua;
          }
        }
        // console.log("买方向：", buyObj);
        // console.log("卖方向：", sellObj);
        if (buyObj.ContractID) {
          buyObj.Quantity = buyQuantity;
          buyObj.AveragePrice = (buyPrice / buyQuantity).toFixed(itemAcc);
          collectList.push(buyObj);
        }

        if (sellObj.ContractID) {
          sellObj.Quantity = sellQuantity;
          sellObj.AveragePrice = (sellPrice / sellQuantity).toFixed(itemAcc);
          collectList.push(sellObj);
        }
      }
      // console.log("汇总数据", collectList);
      this.showCollectList = collectList;
    },
    // 返回行情页面
    backHome (type) {
      console.log(type);
      if (type == 1) {
        this.$router.back(-1);
      } else {
        this.$router.push("/home");
      }

      if (this.winSnap === 1) {
        // 当前界面快照是最大化，返回恢复原状
        ipcRenderer.send("win-msg", "reset"); // 重设配置
        ipcRenderer.send("win-msg", "zoom");
        this.$store.dispatch("bar/updateWinMax", true);
      } else {
        ipcRenderer.send("win-msg", "mini-back", this.oldBounds);
      }
    },
    // 选中合约处理
    selectContract (id) {
      // 不锁定状态下，同时修改store和当前自留合约代码
      this.$store.commit("product/SET_ACTCONTRACT", id);
      console.log("合约选中变化");
    },
    // 选择下单价格
    switchPrice (type) {
      this.priceType = type;
    },
    // 显示报表
    showReport () {
      // 判断当前报表是否展示
      if (this.isShowRep) {
        ipcRenderer.send("win-msg", "hide-report"); // 关闭报表
      } else {
        ipcRenderer.send("win-msg", "show-report"); // 展示报表
      }
      this.isShowRep = !this.isShowRep;
    },
    // 持仓列表table表格选中事件
    switchPosTr (i, item) {
      this.$store.commit("product/SET_ACTCONTRACT", item.ContractID);
      this.ponIndex = i;
      if (this.showPosList[i].Quantity * 1 > 0) {
        this.hands = this.showPosList[i].Quantity;
      }
    },
    // 委托列表table表格选中事件
    switchComTr (i) {
      this.comIndex = i;
    },
    // 计算手数和挂单价
    calculateStep (type, isadd) {
      if (type === 1) {
        // console.log("手数计算");
        if (isadd === 1) {
          this.hands++;
        } else if (isadd === 0 && this.hands > 1) {
          this.hands--;
        }
      }

      if (type === 2) {
        // console.log("挂单价格计算");
        // console.log("最小波动", this.nowMinimum);
        let nowPrice = 0;
        if (isadd === 1) {
          nowPrice = Number(this.price) + this.nowMinimum;
        } else if (isadd === 0 && this.price > 0) {
          nowPrice = Number(this.price) - this.nowMinimum;
        }

        if (this.accuracy > 0) {
          // console.log("当前精度：", this.accuracy);
          // console.log('当前价格：', nowPrice)
          nowPrice = nowPrice.toFixed(this.accuracy);
        }
        this.price = Number(nowPrice);
      }
    },
    // 买卖平仓按钮操作
    handleBtns (type) {
      // console.time("建仓操作服务器响应耗时：");
      // console.time("建仓操作提示完毕耗时：");
      // 买、卖、平按钮操作
      let price = 0; // 当前要发送的给后台的价格

      // 委托建仓(15) 发送：15;合约ID;数量;价格;买卖方向;IP地址;止盈点;止损点;
      // 委托建仓 => 买
      if (type === 1) {
        // 根据选择的价格类型做处理, 对手价默认为相反，市价默认为0
        if (this.priceType === "2") {
          // 当前类型为挂单价
          price = this.price; // 用户调整的价格
        }

        if (this.priceType === "3") {
          // 当前类型为对手价
          price = this.latestSell; // 最新买价
        }
        // console.log("stopScore:", this.stopScore)
        trade.wsSend(
          `15;${this.conid};${this.hands};${price};1;${this.stopScore};${this.stopLoss};0;${this.$store.getters.userip};`
        );
        this.hands = 1;
      }

      // 委托建仓 => 卖
      if (type === 2) {
        if (this.priceType === "2") {
          // 当前类型为挂单价
          price = this.price; // 用户调整的价格
        }

        if (this.priceType === "3") {
          // 当前类型为对手价
          price = this.latestBuy; // 最新买价
        }
        this.$store.dispatch("panel/playTipsAudio", 2);
        trade.wsSend(
          `15;${this.conid};${this.hands};${price};2;${this.stopScore};${this.stopLoss};1;${this.$store.getters.userip};`
        );
        this.hands = 1;
      }

      // 委托平仓(17) 发送：17;合约ID;数量;价格;买卖方向;明细ID;IP;
      // 委托平仓
      if (type === 3) {
        // 当前为disable,则不作任何操作
        // console.log("平");
        // console.log(this.ponIndex);
        if (this.priceType === "2") {
          // 当前类型为挂单价
          price = this.price; // 用户调整的价格
        }

        if (this.priceType === "3") {
          // 当前类型为对手价
          price = this.latestPrice; // 最新买价
        }

        if (this.ponIndex === -1) {
          return;
        }
        // console.log("平仓合约:", this.showPosList[this.ponIndex]);
        if (
          this.showPosList[this.ponIndex] !== undefined &&
          this.showPosList[this.ponIndex].CanBeFlat <= 0
        ) {
          return;
        }

        if (this.showPosList[this.ponIndex].ContractID !== this.conid) {
          return;
        }
        this.$store.dispatch("panel/playTipsAudio", 3); // 平仓声音
        let bz = this.showPosList[this.ponIndex].BusCode == 1 ? 1 : 0
        trade.wsSend(
          `17;${this.conid};${this.hands};${price};${this.showPosList[this.ponIndex].BusCode};${this.showPosList[this.ponIndex].ID};${bz};${this.$store.getters.userip};`
        );
        this.hands = 1;
      }
    },
    // 全部平仓 / 撤单
    operationAll (type) {
      if (this.showPosList.length === 0 && type === 1) {
        this.$message({
          message: this.$t("tip.noFlat"),
          duration: 3000,
          showClose: true,
          type: "warning"
        });
        return;
      }
      if (this.commissionlist.length === 0 && type === 2) {
        this.$message({
          message: this.$t("tip.noReact"),
          duration: 3000,
          showClose: true,
          type: "warning"
        });
        return;
      }
      let sFields = "";
      if (type === 1) {
        // 全部平仓
        this.$store.dispatch("panel/playTipsAudio", 3);
        sFields = "29;" + this.$store.getters.userip + ";";
      } else if (type === 2) {
        // 全部撤单
        this.$store.dispatch("panel/playTipsAudio", 6);
        sFields = "30;" + this.$store.getters.userip + ";";
      }

      trade.wsSend(sFields);
    },
    // 快捷平仓
    quickClosing (type) {
      // 在列表中双击平仓，如果设置中没有设置，则无法双击持仓单平仓
      if (!this.dbclickEve && type === 2) {
        return;
      }
      // 快捷平仓
      if (this.ponIndex === -1) {
        this.$message({
          message: this.$t("tip.selectQuickClose"),
          duration: 3000,
          showClose: true,
          type: "warning"
        });
        return;
      }
      this.$store.dispatch("panel/playTipsAudio", 3);

      let nowContract = this.showPosList[this.ponIndex];
      let detailID = nowContract.ID;

      // 委托平仓(17) 发送：17;合约ID;数量;价格;买卖方向;明细ID;IP;
      let busDir = nowContract.BusCode;
      if (busDir === "买") {
        busDir = "1";
      }
      if (busDir === "卖") {
        busDir = "2";
      }
      let bz = this.showPosList[this.ponIndex].BusCode == 1 ? 1 : 0
      trade.wsSend(
        `17;${nowContract.ContractID};${nowContract.Quantity};0;${busDir};${detailID};${bz};${this.$store.getters.userip};`
      );
    },
    // 撤单
    withdrawal () {
      if (this.comIndex === -1) {
        this.$message({
          message: this.$t("tip.selectRevokeEntrust"),
          duration: 3000,
          showClose: true,
          type: "warning"
        });
        return;
      }

      this.$store.dispatch("panel/playTipsAudio", 6);
      this.$store.dispatch("bar/changeLoadings", {
        status: true,
        msg: this.$t("tip.placeWait")
      });
      let nowData = this.commissionlist[this.comIndex];

      // 委托单取消(16) 发送：16;委托单号;IP;
      trade.wsSend(`16;${nowData.Numbering};${this.$store.getters.userip};`);
    },
    // 市价反手
    Backhand () {
      if (this.ponIndex === -1) {
        this.$message({
          message: this.$t("tip.selectReverseContract"),
          duration: 3000,
          showClose: true,
          type: "warning"
        });
        return;
      }
      let nowContract = this.showPosList[this.ponIndex];
      let sendId = nowContract.ID; // 明细id
      if (this.posRadio === "1") {
        sendId = "0";
      }
      this.$store.dispatch("panel/playTipsAudio", 6);
      //  市价反手（32） 发送：32;合约ID;数量;价格;买卖方向;明细ID;IP;
      let bz = nowContract.BusCode == 1 ? 1 : 0
      trade.wsSend(
        `32;${nowContract.ContractID};${nowContract.Quantity};0;${nowContract.BusCode};${sendId};${bz};${this.$store.getters.userip};`
      );
    },
    // 快捷锁仓
    quickLock () {
      if (this.ponIndex === -1) {
        this.$message({
          message: this.$t("tip.selectQuickLock"),
          duration: 3000,
          showClose: true,
          type: "warning"
        });
        return;
      }
      // 判断当前买卖手数是否一致
      let nowContract = this.showPosList[this.ponIndex];
      let buyQua = 0; // 买方向
      let sellQua = 0; // 卖方向
      // console.log(this.showCollectList);
      // console.log("当前合约", nowContract);
      for (const item of this.showCollectList) {
        // console.log(item);
        // 买方向
        if (
          item.ContractID === nowContract.ContractID &&
          item.BusCode === "1"
        ) {
          buyQua = item.Quantity * 1;
        }
        // 卖方向
        if (
          item.ContractID === nowContract.ContractID &&
          item.BusCode === "2"
        ) {
          sellQua = item.Quantity * 1;
        }
      }
      // console.log("当前买数量", buyQua);
      // console.log("当前卖数量", sellQua);

      // 判断买卖方向手数是否相等
      let count = null; // 锁仓需要补足的手数
      let direction = null; // 锁仓的方向
      // 买比卖多，需要建仓count手卖方向的合约单
      if (buyQua > sellQua) {
        count = Math.abs(buyQua - sellQua);
        direction = "2";
      }

      // 卖比买多，需要建仓多出来的count手买方向的合约单
      if (buyQua < sellQua) {
        count = Math.abs(sellQua - buyQua);
        direction = "1";
      }
      // 买卖一样多
      if (buyQua === sellQua) {
        this.$store.dispatch("panel/playTipsAudio", 1);
        this.$message({
          message: this.$t("tip.noLockout"),
          duration: 3000,
          showClose: true,
          type: "warning"
        });
        return;
      }
      // console.log("锁仓补足数量：", count);
      // console.log("锁仓补足方向：", direction);
      this.$store.dispatch("panel/playTipsAudio", 6);
      let bz = this.showPosList[this.ponIndex].BusCode == 1 ? 1 : 0
      // 发送：15;合约ID;数量;价格;买卖方向;IP地址;止盈点;止损点;
      trade.wsSend(
        // `15;${nowContract.ContractID};${count};0;${direction};${this.$store.getters.userip};0;0;`
        `15;${nowContract.ContractID};${count};0;${direction};0;0;${bz};${this.$store.getters.userip};`
      );
    }
  }
};
</script>

<style lang="scss">
.mini-container {
  .form-item {
    .ivu-input-wrapper.compute-input {
      input[type="number"]::-webkit-outer-spin-button,
      input[type="number"]::-webkit-inner-spin-button {
        -webkit-appearance: none;
      }
      .ivu-input {
        border: 1px solid #99999a;
        padding: 0px 4px;
        height: 24px;
        border-radius: 0;
        outline: none;
        text-align: center;
        &:hover {
          border-color: #99999a;
        }
        &:focus {
          border-color: #99999a;
          box-shadow: none;
        }
      }
    }
    .ivu-select {
      .ivu-select-selection {
        height: 24px;
        border: 1px solid #99999a;
        .ivu-select-placeholder {
          height: 22px;
          line-height: 22px;
        }
        .ivu-select-selected-value {
          height: 22px;
          line-height: 22px;
        }
      }
      .ivu-select-dropdown {
        max-height: 168px;
      }
    }
  }
  .mini-report {
    .ivu-tabs {
      .ivu-tabs-bar {
        margin-bottom: 0;
        .ivu-tabs-nav-container {
          line-height: 1;
        }
      }
    }
  }
}
</style>

<style lang="scss" scoped>
.mini-container {
  position: relative;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  user-select: none;
  min-height: 180px;

  /*滚动条整体样式*/
  ::-webkit-scrollbar {
    width: 10px; /*竖向滚动条的宽度*/
    height: 10px; /*横向滚动条的高度*/
  }
  ::-webkit-scrollbar-thumb {
    /*滚动条里面的小方块*/
    background: #666666;
    border-radius: 5px;
  }
  ::-webkit-scrollbar-track {
    /*滚动条轨道的样式*/
    background: #ccc;
    border-radius: 5px;
  }
  .top-bar {
    width: 100%;
    height: 30px;
    display: flex;
    -webkit-app-region: drag;
    justify-content: space-between;
    background: url("../../assets/img/head-bg1.jpg") repeat-x;
    .content {
      flex: 1;
      display: flex;
      .logo {
        width: 30px;
        height: 30px;
        background: url("../../assets/img/logo.png") no-repeat 5px 6px;
        background-size: 64% 64%;
        margin: 0 4px;
      }
      .currencies {
        .cur-block {
          margin-right: 10px;
          line-height: 30px;
        }
      }
    }

    .back {
      -webkit-app-region: no-drag;
      width: 22px;
      height: 22px;
      margin-top: 4px;
      margin-right: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      border-radius: 3px;
      cursor: move;
      &:hover {
        border: 1px solid #333333;
      }
    }
  }
  .mini-content {
    width: 100%;
    box-sizing: border-box;
    padding: 10px 20px;
    .order-form {
      display: flex;
      width: 100%;
      height: 60px;
      padding-bottom: 12px;
      .form-item {
        flex: 1;
        margin-right: 7px;
        &:nth-last-of-type(1) {
          margin-right: 0;
        }
        &.market {
          background: linear-gradient(to bottom, #f5f2f2 10%, #e0dedf 100%);
          padding: 6px 0;
          border-radius: 4px;
          overflow: hidden;
        }
        .item-label {
          .opt {
            cursor: pointer;
            &.on {
              border: 1px solid #99999a;
              background-color: #b7cffb;
            }
          }
        }

        .item-body {
          padding-top: 5px;
          display: flex;
          .add {
            width: 19px;
            height: 24px;
            text-align: center;
            line-height: 24px;
            border: 1px solid #99999a;
            border-left: none;
            border-radius: 0 4px 4px 0;
            background-color: #b7cffb;
            cursor: pointer;
          }
          .less {
            width: 19px;
            height: 24px;
            text-align: center;
            line-height: 24px;
            border: 1px solid #99999a;
            border-right: none;
            background-color: #b7cffb;
            border-radius: 4px 0 0 4px;
            cursor: pointer;
          }
          .compute-input {
            flex: 1;
          }
        }
        .market-price {
          margin-top: 5px;
          width: 100%;
          height: 24px;
          border: 1px solid #99999a;
          text-align: center;
          line-height: 24px;
          border-radius: 4px;
        }
        .item-buy {
          line-height: 18px;
          padding-left: 10px;
          > span {
            margin-left: 10px;
          }
          .buy {
            color: #ff3c39;
          }
        }

        .item-sell {
          line-height: 18px;
          padding-left: 10px;
          > span {
            margin-left: 10px;
          }
          .sell {
            color: #0bb90b;
          }
        }
      }
    }
    .btn-group {
      display: flex;
      width: 100%;
      height: 60px;
      .handle-btn {
        flex: 1;
        margin-right: 7px;
        &:nth-last-of-type(1) {
          margin-right: 0;
        }
        text-align: center;
        padding: 5px 0px 3px 0px;
        font-size: 18px;
        font-family: sans-serif;
        border: 1px solid #104261;
        border-radius: 3px;
        position: relative;
        background: linear-gradient(to bottom, #fff 0%, #e0dedf 100%);
        cursor: pointer;
        display: flex;
        flex-direction: column;
        flex-wrap: wrap;
        user-select: none;

        &:hover {
          border-color: #de9621;
        }

        &.show-report {
          background: transparent;
          display: flex;
          align-items: center;
          justify-content: center;
          &:hover {
            border-color: #104261;
          }
        }
        .btn-price {
          font-size: 13px;
          min-height: 19px;
        }
        .btn-text {
          position: relative;
          padding-top: 4px;
          &::before {
            position: absolute;
            content: "";
            top: -0px;
            left: 4px;
            right: 4px;
            height: 1px;
            background: #c2c2ba;
          }
          &.buy {
            color: #d80606;
          }
          &.sell {
            color: #14a705;
          }
          &.open {
            color: #0363b7;
          }
        }

        &.buy-disable {
          background: #eee;
          color: #ccc;
          border: 1px solid #cccaca;
          cursor: not-allowed;
          &:hover {
            border-color: #cccaca;
          }
        }
      }
    }
  }
  .mini-report {
    .open-trades {
      display: flex;
      height: 177px;
    }
    .order-ticket {
      display: flex;
      height: 177px;
    }
    .table-box {
      flex: 1;
      overflow: hidden;
      overflow-x: scroll;
      position: relative;
    }
    .handle-box {
      width: 80px;
      display: flex;
      flex-direction: column;
      flex-wrap: wrap;
      align-items: center;
      justify-content: center;
      .btn {
        border-radius: 3px;
        font-size: 12px;
        background: linear-gradient(to bottom, #fff 0%, #e0dedf 100%);
        cursor: pointer;
        color: #191a15;
        outline: none;
        padding: 1px 5px;
        border: 1px solid;
        margin-right: 3px;
        user-select: none;
        margin-bottom: 10px;
      }
    }
    // table 表格样式
    .dTable {
      border: none;
      height: 100%;
      white-space: nowrap;
      overflow-x: auto;

      thead {
        position: absolute;
        width: 720px;
        top: 0;
        height: 22px;
        left: 0;
        background: #fff;
        display: table;
        table-layout: fixed;
        font-size: 12px;
        font-weight: normal;
        text-align: left;

        tr {
          display: table;
          width: 100%;
          table-layout: fixed;

          th {
            text-align: center;
            border-right: 1px solid #b1bbc0;
            border-bottom: 1px solid #b1bbc0;
            padding: 0 2px;
            font-size: 12px;
            line-height: 22px;
            height: 22px;
            font-weight: normal;
            overflow: hidden;

            &:last-child {
              border-right: none;
            }
          }
        }
      }

      tbody {
        width: 720px;
        height: 100%;
        padding-top: 22px;
        box-sizing: border-box;
        display: block;
        overflow-y: scroll;
        color: #000000;

        tr {
          display: table;
          width: 100%;
          table-layout: fixed;

          td {
            text-align: center;
            border: none;
            padding: 0 2px;
            font-size: 12px;
            line-height: 22px;
            height: 22px;
            font-weight: normal;
            overflow: hidden;

            .pricerise {
              color: #ff3c39;
            }

            .pricefall {
              color: #00e700;
            }
          }

          &.noneInfo {
            text-align: center;
            font-size: 12px;
            color: #808080;
            padding: 6px 0;
          }

          &.active {
            background-color: #0078d7;
            color: #fff;
          }

          &.statistics {
            td {
              line-height: 82px;
            }
          }
        }
      }

      &.order {
        width: 1180px;
        thead {
          width: 1180px;
        }
        tbody {
          width: 1180px;
        }
      }
    }
  }
}
</style>
